package com.example.demo.innoket.generate;

import com.example.demo.innoket.util.*;
import com.example.demo.innoket.vo.Table;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;

import java.io.StringWriter;
import java.util.List;

/**
 * jsp 页面模板
 */
public class JspGenerate implements Generate {
	FileType jspFileType = null;

	public JspGenerate(FileType jspFileType) {
		this.jspFileType = jspFileType;
	}

	@SuppressWarnings("static-access")
	public void generate(Table table, GeneratorConfig.ModulePath path) throws Exception {
		if (jspFileType == null)
			throw new Exception(JspGenerate.class.getName() + ": JspFileType 为null");
		/* get the Template */
		Template t = new VelocityUtil().getTemplate(Resources.TEMPLATE_PATH+"/"+jspFileType.getTemplate());

		VelocityContext context = new VelocityContext();

		//获取实例对象名
		String tableName = table.getTableName().toLowerCase();
		StringBuilder sb = new StringBuilder();
		String[] arrs = tableName.split("_");
		if(arrs!=null && arrs.length>0){
			int len = arrs.length;
			if (len > 1) {
				for (int i = 1; i < len; i++) {
					String s = arrs[i];
					sb.append(Character.toUpperCase(s.charAt(0)));
					sb.append(s.substring(1));
				}
			}
		}
		//前缀
		String model = arrs[0].toLowerCase();
		String entityInstance= ConvertHandler.getEntityInstance(tableName);
		String className = ConvertHandler.table2clazzName(tableName);//entityInstance.substring(0,1).toUpperCase()+entityInstance.substring(1,entityInstance.length());
		
		context.put("entityName", className);
		context.put("entityInstance", entityInstance);
		context.put("tableName", table.getTableName().toLowerCase());
		context.put("columns", table.getColumns());
		String tableMemo = table.getPk().getComment();
		context.put("tableMemo", tableMemo);
//		context.put("requestMapping", Resources.JSP_FILE_PACKAGE);
		context.put("moudle", entityInstance);//模块名
		context.put("model", model);//前缀
		String jspFile = new Underline2Camel().camel2Underline(entityInstance).toLowerCase();
		String jsName = jspFile+jspFileType.getFileNameExtension().replace(".jsp", ".js");
		context.put("importJsName", jsName);//前缀
		
		StringWriter writer = new StringWriter();
		t.merge(context, writer);
//		FileUtil.create(Resources.JSP_FILE_PATH +"/"+ Resources.JSP_FILE_PACKAGE+ "/" + model +"/", jspFile +jspFileType.getFileNameExtension(), writer.toString());
	}

	public void generate(List<Table> tables,GeneratorConfig.ModulePath path) throws Exception {
		
	}
	
}
